package com.qdu.controller;

import com.qdu.entity.Collectioninfo;
import com.qdu.entity.Houseinfo;
import com.qdu.service.CollectionService;
import com.qdu.service.HouseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@RestController
@RequestMapping("/collections")
public class CollectionController {

    @Autowired
    private CollectionService collectionService;

    @Autowired
    HouseService houseService;

    @GetMapping("/selectByUid")
    public List findCollectionByUid(String uid){
        List<Collectioninfo> collections = collectionService.getCollectionByUid(uid);
        List<Map> infos = new ArrayList<>();
        for(Collectioninfo c : collections){
            HashMap<String, Object> info = new HashMap<>();
            Houseinfo houseinfo = houseService.selectByHid(c.getHid());
            info.put("house", houseinfo);
            List<String> imgs=new ArrayList<>();
            String img=houseinfo.getHimg();
            String[] is=img.split("!");
            for (String i:is){
                imgs.add(i);
            }
            info.put("cinfo", c);
            info.put("img", imgs.get(0));
            infos.add(info);
        }
        return infos;
    }

    @GetMapping("/selectByHid")
    public List<Collectioninfo> findCollectionByHid(String hid){
        List<Collectioninfo> collections = collectionService.getCollectionByHid(hid);
        return collections;
    }

    @GetMapping("/delete")
    public Result deleteByPrimaryKey(String uid, String hid){
        Result result = new Result();
        try{
            collectionService.deleteCollection(uid, hid);
            result.setMsg("取消收藏成功");
        }catch(Exception ex){
            System.out.println(ex.getMessage());
            result.setStatus(false);
            result.setMsg("系统错误：取消收藏失败，请稍后再试");
        }
        return result;

    }

    @PostMapping("/add")
    public void addCollection(String uid,String hid){
        Collectioninfo collection=new Collectioninfo();
        collection.setCdate(new Date());
        collection.setHid(hid);
        collection.setUid(uid);
        collectionService.addCollection(collection);
    }

}
